package com.test;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.web.bind.annotation.RequestParam;

public class Producer {
    public static final String QUEUE_NAME1 = "消息队列1";
    public static final String QUEUE_NAME2 = "消息队列2";
    public static final String EXCHANGE_NAME = "交换机名称";

    public static void main(String[] args) {
        try {
            // 获取RabbitmqUtils中配置的ConnectionFactory
            ConnectionFactory factory = RabbitmqUtils.getFactory();

            // 确保ConnectionFactory是正确配置的
            factory.setHost(RabbitmqUtils.getHost());
            factory.setPort(RabbitmqUtils.getPort());
            factory.setUsername(RabbitmqUtils.getUsername());
            factory.setPassword(RabbitmqUtils.getPassword());

            // 使用RabbitmqUtils创建通道
            try (Channel channel = factory.newConnection().createChannel()) {
                // 声明交换机
                channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT); // 使用BuiltinExchangeType

                // 发送消息
                for (int i = 1; i <= 10; i++) {
                    String message = "生产了" + i + "个，我勒个骚杠！！";
                    channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
                    System.out.println("生产者发送消息：" + message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



//        //1,得到创建工厂
//        ConnectionFactory factory = new ConnectionFactory();
//        factory.setHost("192.168.159.142");
//        factory.setPort(5672);
//        factory.setUsername("guest");
//        factory.setPassword("guest");
//
//        // java8新的try..catch语法，这种语法的好处是不用我们手动的关闭connection
//        try (Connection connection = factory.newConnection();
//             //2,得到连接
//             Channel channel = connection.createChannel()) {
//            //3,申明交换机
//            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
//            //4,申明队列
//            channel.queueDeclare(QUEUE_NAME1, true, false, false, null);
//            channel.queueDeclare(QUEUE_NAME2, true, false, false, null);
//            //把队列绑定到交换机上
//            channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "");
//            channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "");
//            //5,发送消息
//            for (int i = 1; i <= 10; i++) {
//                String message = "生产了" + i + "个，我勒个骚杠！！";
//                channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
//                System.out.println("生产者发送消息：" + message);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
